package cn.szzsi.common.model;

import cn.szzsi.common.kit.CommonUtil;
import cn.szzsi.common.model.base.BaseMember;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.Map.Entry;

/**
 * 实体类 - 会员
 */
public class Member extends BaseMember<Member> {

    private static final long serialVersionUID = 1312507976941245078L;

    public static final String LOGOUT_URL = "logoutUrl";// 退出登陆时跳转url
    public static final String LOGIN_USER_INFO = "userInfo";// 保存登录会员信息
    public static final String LOGIN_MEMBER_ID_SESSION_NAME = "loginMemberId";// 保存登录会员ID的Session名称
    public static final String LOGIN_CUSTOMER_ID_SESSION_NAME = "logincCustomerId";// 保存登录用户ID的Session名称
    public static final String LOGIN_MEMBER_USERNAME_COOKIE_NAME = "loginMemberUsername";// 保存登录会员用户名的Cookie名称
    public static final String LOGIN_TYPE_COOKIE_NAME = "loginMemberType";// 保存登录类型Cookie名称(business:商户,customer:用户)
    public static final String LOGIN_REDIRECTION_URL_SESSION_NAME = "redirectionUrl";// 保存登录来源URL的Session名称
    public static final String PASSWORD_RECOVER_KEY_SEPARATOR = "_";// 密码找回Key分隔符
    public static final int PASSWORD_RECOVER_KEY_PERIOD = 30;// 密码找回Key有效时间（单位：分钟）
    public static final String USER_JSON = "userJson";//用户信息json

    private Map<String, String> memberAttributeMapStore = new HashMap<String, String>(); // 会员注册项储存

    public static final Member dao = new Member().dao();

    public boolean containEmail(String email) {
        return dao.findFirst("select email from mall_member where email=? limit 1", email) != null;
    }

    public boolean containUsername(String username) {
        return dao.findFirst("select username from mall_member where username=? limit 1", username) != null;
    }

    public Member updateUsername(String username,String shopId,String id){
        return dao.findFirst("select username from mall_member where username=? and shopId=? and id!=?", username,shopId,id);
    }

    /**
     * 获得某人的直谏会员
     *insert(phone, 5, 3, '***')
     * @param member
     * @return
     */
    public List<Member> getFirstRecommendByMember(Member member) {
        return dao.find("select createDate,phone from mall_member where pid = ? order by createDate desc", member.getStr("id"));
    }

    /**
     * 获得某人的所有会员数
     *
     * @param member
     * @return
     */
    public long getRecommendNum(Member member) {
        return Db.queryColumn("select count(*) from mall_member where pids like '%" + member.getStr("id") + "%' order by createDate desc");
    }

    /**
     * 获得某人的所有会员数
     *
     * @param member
     * @return
     */
    public long getfirstRecommendNum(Member member) {
        return Db.queryColumn("select count(*) from mall_member where pid=? order by createDate desc",member.getId());
    }

    /**
     * 获得某人次一级的直谏会员
     *
     * @param member
     * @param level  级别,一般是2、3级
     * @return
     */
    public List<Member> getFirstRecommendByMember(Member member, int level) {
        List<Member> list = dao.find("select * from mall_member where pids like ?", "%" + member.getStr("id") + "%");
        List<Member> members = new ArrayList<Member>();
        String tmp = "";
        try {
            if (level == 2) {
                for (Member m : list) {
                    tmp = org.apache.commons.lang3.StringUtils.substring(m.getStr("pids"), org.apache.commons.lang3.StringUtils.indexOf(m.getStr("pids"), member.getStr("id")));
                    if (org.apache.commons.lang3.StringUtils.countMatches(tmp, ",") == 1) {
                        members.add(m);
                    }
                }
            } else if (level == 3) {
                for (Member m : list) {
                    tmp = org.apache.commons.lang3.StringUtils.substring(m.getStr("pids"), org.apache.commons.lang3.StringUtils.indexOf(m.getStr("pids"), member.getStr("id")));
                    if (org.apache.commons.lang3.StringUtils.countMatches(tmp, ",") == 2) {
                        members.add(m);
                    }
                }
            }
        } catch (Exception e) {

        }
        return members;
    }


    /**
     * 根据用户名判断此用户是否存在（不区分大小写）
     */
    public boolean isExistByCustomerUsername(String username, String shopId) {
        String sqlMember = "select * from mall_member where lower(username) = lower(?) and shopId=?";
        String sqlAdmin = "select * from mall_admin where lower(username) = lower(?)";
        Member member = dao.findFirst(sqlMember, username, shopId);
        Admin admin = Admin.dao.findFirst(sqlAdmin, username);
        if (member != null || admin != null) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 根据用户名获取会员对象，若会员不存在，则返回null（不区分大小写）
     * 验证平台用户.......
     */
    public Member getMemberByUsername(String username) {
        return dao.findFirst("select * from mall_member where username = ? and shopId ='-1' ", username);
    }


    /**
     * 根据用户名获取会员对象，若会员不存在，则返回null（不区分大小写）
     */
    public Member getBusinessByUsername(String username) {//验证商户
        return dao.findFirst("select * from mall_member where username = ? and shopId ='0' ", username);
    }

    /**
     * 根据用户名,手机号,邮箱,获取会员对象，若会员不存在，则返回null（不区分大小写）
     * @param username
     * @return
     */
    public Member getBusinessByAll(String username) {//验证商户
        Member member=dao.findFirst("select * from mall_member where username = ? and shopId ='0' ", username);
        if(member!=null){
             return member;
        }else{
            return null;
        }

    }



    /**
     * 根据用户名获取会员对象，若会员不存在，则返回null（不区分大小写）
     * 验证商户用户
     */
    public Member getCustomerByUsername(String username) {
        return dao.findFirst("select * from mall_member where username = ? and shopId !='-1' and shopId!='0' ", username);
    }

    /**
     * 根据用户名获取会员对象，若会员不存在，则返回null（不区分大小写）
     */
    public Member getCustomerByUsernameAndShopId(String username, String shopId) {//验证商户的用户
        return dao.findFirst("select * from mall_member where (username = ? or phone=?) and shopId=? ", username,username, shopId);
    }

    /**
     * 根据用户名判断此用户是否存在（不区分大小写）
     */
    public boolean isExistByUsername(String username) {
        String sqlMember = "select * from mall_member where lower(username) = lower(?) and shopId='-1'";
        String sqlAdmin = "select * from mall_admin where lower(username) = lower(?)";
        Member member = dao.findFirst(sqlMember, username);
        Admin admin = Admin.dao.findFirst(sqlAdmin, username);
        if (member != null || admin != null) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据用户名判断此用户是否存在（不区分大小写）
     */
    public boolean isExistByUsername(String username, String shopId) {
        String sqlMember = "select * from mall_member where lower(username) = lower(?) and shopId=?";
        String sqlAdmin = "select * from mall_admin where lower(username) = lower(?)";
        Member member = dao.findFirst(sqlMember, username, shopId);
        Admin admin = Admin.dao.findFirst(sqlAdmin, username);
        if (member != null || admin != null) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断用户名或者手机号是否存在
     * @param phone
     * @return
     */
    public Member verifyCustomerByUsernameOrPhone(String phone,String password) {
        String sqlMember = "select * from mall_member where lower(username) = lower(?) or phone=?";
        Member member = dao.findFirst(sqlMember, phone, phone);
        if(member!=null && member.getPassword().equals(DigestUtils.md5Hex(password))){
            return member;
        }else{
            return null;
        }

    }






    /**
     * 根据用户名、密码验证会员
     *
     * @param username 用户名
     * @param password 密码
     * @return 验证是否通过
     */
    public boolean verifyCustomer(String username, String password, String shopId) {
        Member member = getCustomerByUsernameAndShopId(username, shopId);
        if (member != null && member.getPassword().equals(DigestUtils.md5Hex(password))) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据用户名、密码验证会员
     *
     * @param member 商户实体
     * @param password 密码
     * @return 验证是否通过
     */
    public boolean verifyMember(Member member, String password) {
        if (member != null && member.getStr("password").equals(DigestUtils.md5Hex(password))) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据用户名、密码验证会员
     *
     * @param username 用户名
     * @param password 密码
     * @return 验证平台用户是否通过
     */
    public boolean verifyCustomerMember(String username, String password) {
        Member member = getMemberByUsername(username);
        if (member != null && member.getStr("password").equals(DigestUtils.md5Hex(password))) {
            return true;
        } else {
            return false;
        }
    }

    // 获取会员注册项
    public Map<String, String> getMemberAttributeMap() {
        String sql = "select * from mall_member_memberattributemapstore where member_id = ?";
        List<MemberAttributeMapstore> memberAttributeList = MemberAttributeMapstore.dao.find(sql, getStr("id"));

        if (memberAttributeList != null && memberAttributeList.size() > 0) {
            for (MemberAttributeMapstore memberAttribute : memberAttributeList) {
                memberAttributeMapStore.put(memberAttribute.getStr("mapkey_id"), memberAttribute.getStr("element"));
            }
        }
        return memberAttributeMapStore;
    }

    // 设置会员注册项
    public void setMemberAttributeMap(Map<String, String> memberAttributeMap) {
        if (memberAttributeMap == null || memberAttributeMap.size() == 0) {
            memberAttributeMapStore = null;
            return;
        }
        // 先删除已存的
        Db.deleteById("member_memberattributemapstore", "member_id", getStr("id"));
        // 再保存
        MemberAttributeMapstore memberAttribute = new MemberAttributeMapstore();
        for (Entry<String, String> entry : memberAttributeMap.entrySet()) {
            memberAttribute.set("member_id", getStr("id"));
            memberAttribute.set("mapkey_id", entry.getKey());
            memberAttribute.set("element", entry.getValue());
            memberAttribute.save();
        }
    }


    /**
     * 生成密码找回Key
     *
     * @return 密码找回Key
     */
    public String buildPasswordRecoverKey() {
        return System.currentTimeMillis() + Member.PASSWORD_RECOVER_KEY_SEPARATOR + CommonUtil.getUUID() + DigestUtils.md5Hex(CommonUtil.getRandomString(10));
    }

    /**
     * 根据密码找回Key获取生成日期
     *
     * @return 生成日期
     */
    public Date getPasswordRecoverKeyBuildDate(String passwordRecoverKey) {
        long time = Long.valueOf(StringUtils.substringBefore(passwordRecoverKey, Member.PASSWORD_RECOVER_KEY_SEPARATOR));
        return new Date(time);
    }

    /**
     * 获取所有实体对象总数.
     *
     * @return 实体对象总数
     */
    public Long getTotalCount() {
        String sql = "select count(*) from mall_member ";
        return Db.queryLong(sql);
    }

    // 等级
    public MemberRank getMemberRank() {
        String sql = "select * from mall_member_rank where id = ? order by createDate desc";
        return MemberRank.dao.findFirst(sql, getStr("memberRankId"));
    }

    // 订单项
    public List<Orders> getOrderList() {
        String sql = "select * from mall_orders where member_id = ? order by createDate desc";
        return Orders.dao.find(sql, getStr("id"));
    }

    // 购物车项
    public List<CartItem> getCartItemList() {
        String sql = "select * from mall_cart_item where member_id = ? order by createDate desc";
        return CartItem.dao.find(sql, getStr("id"));
    }

    // 收货地址
    public List<Receiver> getReceiverList() {
        return Receiver.dao.getReceiverList(this);
    }

    // 默认收货地址
    public Receiver getDefaultReceiver() {
        return Receiver.dao.getDefaultReceiver(this);
    }

    // 预存款充值记录
    public List<Deposit> getDepositList() {
        String sql = "select * from mall_deposit where member_id = ? order by createDate desc ";
        return Deposit.dao.find(sql, getStr("id"));
    }

    // 预存款
    public Deposit getDepositValue() {
        String sql = "select * from mall_deposit where member_id = ? order by createDate desc ";
        return Deposit.dao.findFirst(sql, getStr("id"));
    }

    // 收藏夹商品
    public List<Product> getFavoriteProductList() {
        String sql = "SELECT p.* from mall_member_product m LEFT JOIN mall_product p ON m.favoriteProductSet_id = p.id WHERE m.favoriteMemberSet_id = ?";
        return Product.dao.find(sql, getStr("id"));
    }

    // 收件箱消息
    public List<Message> getInboxMessageList() {
        String sql = "select * from mall_message t where t.toMember_id = ? ";
        return Message.dao.find(sql, getStr("id"));
    }

    // 发件箱消息
    public List<Message> getOutboxMessageList() {
        String sql = "select * from mall_message t where t.fromMember_id = ? ";
        return Message.dao.find(sql, getStr("id"));
    }

    public Member isExistByOpenid(String openid) {
        return Member.dao.findFirst("select * from mall_member where openid=?", openid);
    }

    public Member getByOpenid(String openid) {
        return Member.dao.findFirst("select * from mall_member where openid=?", openid);
    }

    public Member getByMiniOpenid(String miniOPenId) {
        return Member.dao.findFirst("select * from mall_member where miniOPenId=?", miniOPenId);
    }

    //保存微信拉取的用户信息
    public static final Member saveMemberInfo(String pid, String pids, String openid, String username, String sex, String country, String province, String city, String headimgurl, String privilege, String unionid, String shopId, String registerIp, String code) {
        Member member = new Member();
        member.set("pid", pid);
        member.set("pids", pids);
        member.set("openid", openid);
        if (StrKit.isBlank(sex)) {
            sex = "0";
        }
        member.set("sex", sex);
        member.set("country", country);
        member.set("province", province);
        member.set("city", city);
        member.set("headimgurl", headimgurl);
        member.set("privilege", privilege);
        member.set("unionid", unionid);
        member.set("id", CommonUtil.getUUID());
        member.set("username", username);
        member.set("password", openid);
        member.set("shopId", shopId);
        member.set("safeQuestion", null);
        member.set("safeAnswer", null);
        member.set("memberRankId", null);
        member.set("point", 0);
        member.set("deposit", new BigDecimal("0"));
        member.set("isAccountEnabled", true);
        member.set("isAccountLocked", false);
        member.set("loginFailureCount", 0);
        member.set("passwordRecoverKey", null);
        member.set("lockedDate", null);
        member.set("loginDate", new Date());
        member.setSourceType("2");
        if (StrKit.isBlank(registerIp)) {
            registerIp = "127.0.0.1";
        }
        member.set("registerIp", registerIp);
        member.set("loginIp", registerIp);
        member.set("createDate", new Date());
        member.set("code", code);
        member.save();
        return member;
    }

    public static Member saveOauthMemberInfo(String pid, String pids, String openid, String username, String sex, String province, String city, String headimgurl, String shopId, String registerIp, String code){
        Member member = new Member();
        member.set("pid", pid);
        member.set("pids", pids);
        member.set("openid", openid);
        if (StrKit.isBlank(sex)) {
            sex = "0";
        }
        member.set("sex", sex);
        member.set("province", province);
        member.set("city", city);
        member.set("headimgurl", headimgurl);

        member.set("id", CommonUtil.getUUID());
        member.set("username", username);
        member.set("password", openid);
        member.set("shopId", shopId);
        member.set("safeQuestion", null);
        member.set("safeAnswer", null);
        member.set("memberRankId", MemberRank.dao.getDefaultMemberRank(shopId).getStr("id"));
        member.set("point", 0);
        member.set("deposit", new BigDecimal("0"));
        member.set("isAccountEnabled", true);
        member.set("isAccountLocked", false);
        member.set("loginFailureCount", 0);
        member.set("passwordRecoverKey", null);
        member.set("lockedDate", null);
        member.set("loginDate", new Date());
        if (StrKit.isBlank(registerIp)) {
            registerIp = "127.0.0.1";
        }
        member.set("registerIp", registerIp);
        member.set("loginIp", registerIp);
        member.set("createDate", new Date());
        member.set("code", code);
        member.save();
        return member;
    }

    public Role getByRoleId() {
        return Role.dao.findById(getStr("roleId"));
    }

    public void init() {
        String roleId = this.getStr("roleId");
        Role br = Role.dao.findById(roleId);
        this.put("roleName", br == null ? "" : br.getStr("name"));
    }

    public UserBalance getUserBalance() {
        return UserBalance.dao.findByMemberId(getStr("id"));
    }

    /**
     * L 通过套餐id拿到套餐名并设置给member_list,设置省市区三联动数据
     */
    public void initPackageName() {
        this.put("pca", this.getStr("province") + "/" + this.getStr("city") + "/" + this.getStr("area"));
        BusinessPackage businessPackage = BusinessPackage.dao.findById(this.getStr("packageId"));
        if (businessPackage != null) {
            this.put("packageName", businessPackage.getStr("name"));
        }
    }

    /**
     * 获取会员等级
     */
    public MemberRank getMemberRankValue(){
        String memberRankId=getMemberRankId();
        MemberRank memberRank=MemberRank.dao.findById(memberRankId);
        return memberRank;

    }

    /**
     *
     * @param phone
     * @param shopId
     * @return
     */
    public Member getByPhoneAndShopId(String phone,String shopId) {
        return dao.findFirst("select * from mall_member where phone = ? and shopId=?", phone,shopId);
    }


    /**
     * 根据手机号获取会员对象(平台)
     * @param phone
     */
    public Member getByPhone(String phone){
        return dao.findFirst("select * from mall_member where phone = ?", phone);
    }

    /**
     * 根据推荐码获取会员对象(平台)
     * @param code
     * @return
     */
    public Member getByCode(String code){
        return dao.findFirst("select * from mall_member where code = ?", code);
    }

    public Member getByUnionid(String unionid){
        return dao.findFirst("select * from mall_member where unionid = ?", unionid);
    }

    /**
     *
     * @param member
     * @param password
     * @return
     */
    public boolean verifyCustomerByPassword(Member member, String password) {
        if (member.getPassword().equals(DigestUtils.md5Hex(password))) {
            return true;
        } else {
            return false;
        }
    }





}
